package com.example.smartcity.ui.AllService.SmartBus.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import androidx.appcompat.app.AlertDialog
import com.example.smartcity.App.Companion.context
import com.example.smartcity.App.Companion.getToken
import com.example.smartcity.R
import com.example.smartcity.databinding.ActivitySmartBusShowContentBinding
import com.example.smartcity.logic.Repository
import com.example.smartcity.logic.Repository.coroutine
import com.example.smartcity.logic.Repository.sApi
import com.example.smartcity.logic.util.Util.show
import kotlinx.coroutines.Dispatchers
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject


/**
 * 智慧巴士 - 第四页面
 * 显示第三页面所填写的信息， 并点击提交按钮提交订单
 */
class SmartBusShowContentActivity : AppCompatActivity() {

    // 获取类名
    private val tag = this::class.java.simpleName

    // 路线Id
    private val lineID by lazy { intent.getStringExtra("lineID") }
    // 日期
    private val date by lazy { intent.getStringExtra("date") }
    // 用户姓名
    private val edName by lazy { intent.getStringExtra("edName") }
    // 联系电话
    private val edPhone by lazy { intent.getStringExtra("edPhone") }
    // 上车地点
    private val edStartPlace by lazy { intent.getStringExtra("edStartPlace") }
    // 下车地点
    private val edEndPlace by lazy { intent.getStringExtra("edEndPlace") }


    private lateinit var mBinding: ActivitySmartBusShowContentBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivitySmartBusShowContentBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        // 显示回退按钮
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        // 设置标题
        title = "提交订单"

        // 把当前意图添加到数组中
        Repository.smartAddActivity(this)

        // 日志
        Log.d(tag, """
            id -> $lineID
            date -> $date
            name -> $edName
            phone -> $edPhone
            edStartPlace -> $edStartPlace
            edEndPlace -> $edEndPlace
        """.trimIndent())


        showContent()


        // 点击按钮提交订单
        // 监听按钮事件
        mBinding.btn.setOnClickListener {
            onClickPost()
        }

    }

    /**
     * 显示信息
     */
    private fun showContent() {
        mBinding.TvLine.text = "$edStartPlace ----> $edEndPlace"
        mBinding.tvName.text = "用户姓名: ${edName}"
        mBinding.tvPhone.text = "联系电话: ${edPhone}"
        mBinding.tvStartPlace.text = "上车地点: ${edStartPlace}"
        mBinding.tvEndPlace.text = "下车地点: ${edEndPlace}"
    }


    /**
     * 提交信息
     */
    private fun onClickPost() = coroutine(Dispatchers.IO) {
        // 先查询路线ID获取几号线
        sApi.getLineMsg(lineID!!).apply {
            // 获取价格
            val price = this.data?.price
            // 获取路线名称
            val pathName = this.data?.name

            // 发起网络请求(提交订单)
            val result = sApi.setBusOrders(getToken, JSONObject().apply {
                put("start", edStartPlace.toString())
                put("end", edEndPlace.toString())
                put("price", price.toString())
                put("path", pathName.toString())
                put("status", 1)
            }.toString().toRequestBody("application/json".toMediaType()))


            // 判断是否提交成功
            if (result.code == 200) {
                runOnUiThread {
                    // 提交成功的话我们弹窗提示用户
                    AlertDialog.Builder(this@SmartBusShowContentActivity).apply {
                        // 设置提示内容
                        setMessage("提交成功!")
                        // 显示ok按钮
                        setNegativeButton("确定") {_, _ ->
                            // 销毁数组中的Activity
                            Repository.smartMoveAllActivity()
                        }
                        show()
                    }
                }
            } else runOnUiThread {
                result.msg?.show()
            }
        }

    }

    /**
     * 监听回退按钮
     */
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // 销毁该页面
        finish()
        return super.onOptionsItemSelected(item)
    }
}